import React from 'react';
import {
  DeviceEventEmitter,
  Dimensions,
  Image,
  ImageBackground,
  StyleSheet,
  Text,
  TouchableHighlight,
  View,
} from 'react-native';
import Row from 'react-native-cdy-baseui/components/Row';
import {Select} from 'teaset';
import LinearGradient from 'react-native-linear-gradient';
import ImageConstants from '../resources/ImageConstants';
import HttpUtil from 'react-native-cdy-baseui/network/HttpUtil';
import ToastUtil from 'react-native-cdy-baseui/utils/ToastUtil';
import API from '../utils/API';
import DeviceInfo from 'react-native-device-info';
import ModalViewUtil from 'react-native-cdy-baseui/utils/ModalViewUtil';
import Ionicons from 'react-native-vector-icons/Ionicons';
import LoginView from '../views/LoginView';
import AsyncStorage from '@react-native-community/async-storage';
import BasePageV5 from 'react-native-cdy-baseui/components/BasePageV5';

const WIN_WIDTH = Dimensions.get('window').width;

import {
  heightByPercent,
  responsiveNumber,
  responsiveNumber as w,
  widthByPercent,
} from 'react-native-responsive-number/src/index';

//系统设置
class SettingPage extends BasePageV5 {
  constructor(props) {
    super(props);
    this.state = {elecCards: [], elecCard: null};
  }

  async didFocus(first) {
    super.didFocus(first);
    if (!HttpUtil.getUser()) {
      ModalViewUtil.showFromCenter(
        <LoginView loginComplete={(user, bind) => this.getAllElecCards()} />,
        true,
      );
    } else {
      this.getAllElecCards();
    }
  }

  async getAllElecCards() {
    try {
      const {data} = await HttpUtil.post(
        'stadium/electronicClassCardBind/api/queryElectronicClassCardBindList?route=stadium',
        {
          page: 1,
          limit: 999,
        },
      );
      console.log(JSON.stringify(HttpUtil.getItem('ROOM_INFO')));
      this.setState({
        elecCards: data.data,
        elecCard: HttpUtil.getItem('ROOM_INFO')
          ? data.data.find(
              v =>
                v.laboratoryId === HttpUtil.getItem('ROOM_INFO').laboratoryId,
            )
          : null,
      });
    } catch (e) {
      console.log(e);
      if (e.code === '99999') {
        ModalViewUtil.showFromCenter(
          <LoginView loginComplete={(user, bind) => this.getAllElecCards()} />,
          true,
        );
      } else {
        this.showErrorMessage(e.message);
      }
    }
  }
  getItemText = (item, index) => {
    return (
      <View
        style={{
          flex: 1,
          width: WIN_WIDTH * 0.5,
          backgroundColor:
            this.state.elecCard && this.state.elecCard === item
              ? '#46BE88'
              : 'transparent',
        }}>
        <Text
          style={{
            color:
              this.state.elecCard && this.state.elecCard === item
                ? 'white'
                : '#333',
            fontSize: responsiveNumber(10),
          }}>
          {item.electronicClassCardName}-{item.merchantName}
        </Text>
      </View>
    );
  };

  renderContent() {
    return (
      <View style={{flex: 1, width: '100%', alignItems: 'center'}}>
        <Image
          source={ImageConstants.IMG_BCG}
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
          }}
        />
        <Image
          source={ImageConstants.IMG_SHADOW}
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
          }}
        />

        <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
          <Row style={{justifyContent: 'center'}}>
            <Text
              style={{
                fontSize: responsiveNumber(12),
                color: 'white',
                marginRight: responsiveNumber(30),
              }}>
              班牌选择:
            </Text>
            <Select
              iconTintColor={'#44BC86'}
              valueStyle={styles.selectValueStyle}
              style={styles.selectStyle}
              ref={v => (this.select1 = v)}
              onSelected={(item, index) => {
                this.setState({elecCard: this.state.elecCards[index]});
              }}
              value={this.state.elecCard}
              pickerType={'popover'}
              editable={HttpUtil.getUser()}
              getItemValue={(item, index) => item}
              items={this.state.elecCards}
              getItemText={this.getItemText}
              popoverStyle={{width: WIN_WIDTH * 0.5}}
              icon={
                <View style={{width: 60}}>
                  <Ionicons
                    name={'ios-chevron-down'}
                    size={60}
                    color={'#44BC86'}
                  />
                </View>
              }
            />
          </Row>

          <View style={{marginTop: heightByPercent(20)}}>
            <TouchableHighlight onPress={this.showPasswordInputView}>
              <LinearGradient
                colors={['#6FC5C3', '#6FC5C3']}
                start={{x: 0, y: 0}}
                end={{x: 1, y: 0}}
                style={styles.linearGradient}>
                <Text style={styles.buttonText}>{'绑定'}</Text>
              </LinearGradient>
            </TouchableHighlight>
          </View>
        </View>
      </View>
    );
  }

  showPasswordInputView = () => {
    if (this.state.elecCard) {
      this.bindDevice();
    } else {
      // this.getAllElecCards()
      ToastUtil.show('请选择班牌之后再提交');
    }
  };
  bindDevice = async text => {
    try {
      let uniqueId = DeviceInfo.getUniqueId(); //DeviceInfo.getUniqueId();
      await HttpUtil.post(API.UPDATE_CLASS_CARD_API, {
        electronicClassCardBindId:
          this.state.elecCard.electronicClassCardBindId,
        merchantId: this.state.elecCard.merchantId,
        laboratoryId: this.state.elecCard.laboratoryId,
        electronicClassCardNum: this.state.elecCard.electronicClassCardNum,
        electronicClassCardName: this.state.elecCard.electronicClassCardName,
        programmeId: this.state.elecCard.programmeId,
        electronicClassCardId: uniqueId,
      });
      ToastUtil.show('提交成功');
      AsyncStorage.setItem('ROOM_INFO', JSON.stringify(this.state.elecCard));
      HttpUtil.setItem('ROOM_INFO', this.state.elecCard);
      DeviceEventEmitter.emit('showMenus');
      this.navigatePage('TabComponent');
    } catch (e) {
      ToastUtil.show(e.message);
      ModalViewUtil.dismissBottomView();
    }
  };
}

const styles = StyleSheet.create({
  selectStyle: {
    width: widthByPercent(50),
    borderColor: '#46BE88',
    backgroundColor: '#112E32',
    height: responsiveNumber(20),
  },
  selectValueStyle: {
    color: 'white',
    fontSize: responsiveNumber(12),
  },
  linearGradient: {
    paddingLeft: w(30),
    paddingRight: w(30),
    borderRadius: w(44),
    height: responsiveNumber(30),
    width: widthByPercent(50),
  },
  buttonText: {
    fontSize: responsiveNumber(10),
    textAlign: 'center',
    margin: responsiveNumber(8),
    color: '#ffffff',
    backgroundColor: 'transparent',
  },
});
export default SettingPage;
